import Food from './Food'
import Panel from './Panel'
import Snake from './Snake'




export default class GameControl {
    //蛇
    snake: Snake
    //食物
    food: Food
    //记分牌
    panel: Panel
    //创建一个属性用来记录蛇的移动反向
    direction: string
    //创建一个属性记录游戏是否结束
    isLive: boolean = true
    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.panel = new Panel()
        this.init()
    }

    //初始化方法
    init() {
        //绑定键盘按下的事件
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()
    }

    //键盘按下响应
    keydownHandler(event: KeyboardEvent) {
        console.log(event.key)
        //检查event.key的值是否合法
        //修改direction
        this.direction = event.key
    }

    //创建一个控制蛇移动的方法
    run() {
        /* 
        *   根据方向this.direction使蛇位置改变
        *   向上 top减少   
        *   向下 top增加
        *   向左 left减少
        *   向右 left增加
        */

        //获取蛇现在的坐标
        let X = this.snake.headX
        let Y = this.snake.headY
        switch (this.direction) {
            case 'ArrowUp':
                Y -= 10
                break;
            case 'ArrowDown':
                Y += 10
                break;
            case 'ArrowLeft':
                X -= 10
                break;
            case 'ArrowRight':
                X += 10
                break;
        }
        this.eat(X,Y)
        try {
            this.snake.headX = X
            this.snake.headY = Y
           
            
        } catch (e) {
            this.isLive = false
            alert(e.message)
        }
        
        // 开启定时调用
        
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.panel.level - 1) * 30)
    }

    // 检查蛇是否迟到食物
    eat(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            console.log('迟到食物了')
            this.panel.addScore()
            this.food.change()
            this.snake.addBody()
        }
    }
}